package com.jinzhi.jzweb.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.common.controller.ApittController;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.moduleConfig.TrackDrawDO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <pre>
 * 考试批次 理论竞赛控制器
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Slf4j
@Controller
@RequestMapping("/jzweb/examinationBatch")
public class ExaminationBatchController extends BaseController {
    @Autowired
    private ExaminationBatchComService examinationBatchService;

    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private TemplateDetailsService templateDetailsService;
    @Autowired
    private ExaminationPaperService examinationPaperService;
    @Autowired
    private ExaminationQuestionsService examinationQuestionsService;
    @Autowired
    private ItemBankService itemBankService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private UserService userService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private ExaminationAnswerSheetService examinationAnswerSheetService;
    @Autowired
    private DictService dictService;
    @Autowired
    private ApittController apittController;
    @Autowired
    private KnowledgePointsService knowledgePointsService;

    @GetMapping()
    @RequiresPermissions("jzweb:examinationBatch:examinationBatch")
    String ExaminationBatch(Integer type,Model model) {
        model.addAttribute("type",type);
        return "jzweb/examinationBatch/examinationBatch";
    }

    @ResponseBody
    @GetMapping("/list")
    //@RequiresPermissions("jzweb:examinationBatch:examinationBatch")
    public Result<Page<ExaminationBatchComDO>> list(ExaminationBatchComDO examinationBatchDTO) {
        Wrapper<ExaminationBatchComDO> wrapper = new EntityWrapper<ExaminationBatchComDO>().orderBy("id", false);
        if (examinationBatchDTO.getState() != null) {
            wrapper.eq("state", examinationBatchDTO.getState());
        }
        if (examinationBatchDTO.getType() != null) {
            wrapper.eq("type", examinationBatchDTO.getType());
        }
        if (examinationBatchDTO.getName() != null) {
            wrapper.like("name", examinationBatchDTO.getName());
        }
        if (StringUtils.isNotBlank(examinationBatchDTO.getCbatchName())) {
            Wrapper<CertificationBatchDO> cbatWrapper = new EntityWrapper<CertificationBatchDO>().like("name", examinationBatchDTO.getCbatchName());
            List<CertificationBatchDO> certificationBatchDOS = certificationBatchService.selectList(cbatWrapper);
            String str = "";
            for (CertificationBatchDO certificationBatchDO : certificationBatchDOS) {
                str = str + certificationBatchDO.getId() + ",";
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("cbatch_id", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("cbatch_id", null);
            }
        }

        Page<ExaminationBatchComDO> page = examinationBatchService.selectPage(getPage(ExaminationBatchComDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExaminationBatchComDO obj = (ExaminationBatchComDO) page.getRecords().get(i);
            if (obj.getCbatchId() != null) {
                CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(obj.getCbatchId());
                if (certificationBatchDO != null) {
                    obj.setCbatchName(certificationBatchDO.getName());
                }
            }
            //审核用户名
            if (obj.getCheckerId() != null) {
                UserDO userDO = userService.selectById(obj.getCheckerId());
                if (userDO != null) {
                    obj.setCheckerName(userDO.getUsername());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:examinationBatch:add")
    String add(Model model) {
        model.addAttribute("certificationBatch", certificationBatchService.selByNameId());
        return "jzweb/examinationBatch/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:examinationBatch:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        model.addAttribute("certificationBatch", certificationBatchService.selByNameId());
        ExaminationBatchComDO examinationBatch = examinationBatchService.selectById(id);
        model.addAttribute("examinationBatch", examinationBatch);
        return "jzweb/examinationBatch/edit";
    }

    @Log("添加考试批次")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:examinationBatch:add")
    public Result<String> save(ExaminationBatchComDO examinationBatch) {
        //根据认证批次id、考试批次名称判断考试批次是否重复
//        ExaminationBatchDO examinationBatchDO = examinationBatchService
//                .findOneByKv("name", examinationBatch.getName(),"type", examinationBatch.getType(), "cbatch_id", examinationBatch.getCbatchId());
        long m = ((examinationBatch.getEndTime().getTime()-examinationBatch.getStartTime().getTime())/1000/60);

        if(examinationBatch.getBatchType().equals("2")){

            Map<String, String> map1 = new HashMap<>();
            map1.put("name", "理论考试时间最小值（分钟）");
            map1.put("type", "exam_time_min");
            int min =Integer.parseInt(dictService.selDicBy(map1));
            Map<String, String> map2 = new HashMap<>();
            map2.put("name", "理论考试时间最大值（分钟）");
            map2.put("type", "exam_time_max");
            int max =Integer.parseInt(dictService.selDicBy(map2));
            if(m<min || m>max) {
                return Result.fail("考试批次时间设置错误,考试时间应在 "+min+"-"+max+"分钟之间！");
            }
        }

//        if (examinationBatchDO != null) {
//            return Result.fail("考试批次已存在！（考试批次名称相同的情况下，可以有多个考试批次类型）");
//        } else {
            examinationBatchService.insert(examinationBatch);
            return Result.ok();
       // }
    }

    @Log("修改考试批次")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:examinationBatch:edit")
    public Result<String> update(ExaminationBatchComDO examinationBatch) {
        //根据认证批次id、考试批次名称判断考试批次是否重复
        List<ExaminationBatchComDO> examinationBatchDO = examinationBatchService
                .findByKv("name", examinationBatch.getName(),"type", examinationBatch.getType(), "cbatch_id", examinationBatch.getCbatchId());
        long m = ((examinationBatch.getEndTime().getTime()-examinationBatch.getStartTime().getTime())/1000/60);
    if(examinationBatch.getBatchType().equals("2")){

        Map<String, String> map1 = new HashMap<>();
        map1.put("name", "理论考试时间最小值（分钟）");
        map1.put("type", "exam_time_min");
        int min =Integer.parseInt(dictService.selDicBy(map1));
        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "理论考试时间最大值（分钟）");
        map2.put("type", "exam_time_max");
        int max =Integer.parseInt(dictService.selDicBy(map2));
        if(m<min || m>max) {
            return Result.fail("考试批次时间设置错误,考试时间应在 "+min+"-"+max+"分钟之间！");
        }
    }
        if (examinationBatchDO != null && examinationBatchDO.size() > 0) {
            if (examinationBatchDO.size() == 1) {
                if (examinationBatchDO.get(0).getId().equals(examinationBatch.getId())) {
                    boolean update = examinationBatchService.updateById(examinationBatch);
                    return update ? Result.ok() : Result.fail();
                }
            }
            return Result.fail("考试批次已存在！（考试批次名称相同的情况下，可以有多个考试批次类型）");
        } else {
            boolean update = examinationBatchService.updateById(examinationBatch);
            return update ? Result.ok() : Result.fail();
        }
    }

    @Log("删除考试批次")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationBatch:remove")
    public Result<String> remove(Long id) {
        ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", id);
        if (examinationPaperDO != null) {
            return Result.fail("请先删除试卷后再来删除考试批次！");
        } else {
            ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(id);
            if (examinationBatchDO.getState() == 3 || examinationBatchDO.getState() == 4 || examinationBatchDO.getState() == 5 || examinationBatchDO.getState() == 6) {
                return Result.fail("根据当前考试批次状态判断，该数据暂不允许删除！");
            } else {
                examinationBatchService.deleteById(id);
            }
            return Result.ok();
        }

    }

    @Log("批量删除考试批次")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationBatch:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {

        boolean b = true;
        boolean a = true;
        for (int i = 0; i < ids.length; i++) {
            ExaminationPaperDO examinationPaperDO = examinationPaperService.findOneByKv("ebatch_id", ids[i]);
            if (examinationPaperDO == null) {
                ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(ids[i]);
                if (examinationBatchDO.getState() == 3 || examinationBatchDO.getState() == 4 || examinationBatchDO.getState() == 5 || examinationBatchDO.getState() == 6) {
                    b = false;
                }
            } else {
                a = false;
            }
        }

        if (a) {
            if (b) {
                examinationBatchService.deleteBatchIds(Arrays.asList(ids));
                return Result.ok();
            } else {
                return Result.fail("根据当前考试批次状态判断，该数据中存在：开始登录、考试中、已考完、已生成试卷等状态数据，暂不允许删除！");
            }
        } else {
            return Result.fail("有考试批次存在试卷未删除，请先删除对应试卷后重试！");
        }
    }

    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    @RequiresPermissions("jzweb:examinationBatch:review")
    public Result<String> review(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {
        if (state.equals(2) || state.equals(1)) {
            int i = 0;
            for (Long id : ids) {
                ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(id);
                if (examinationBatchDO != null) {
                    examinationBatchDO.setState(state);
                    examinationBatchDO.setCheckerId(this.getUserId());
                    examinationBatchDO.setCheckerDate(new Date());
                    if (state.equals(2)) {
                        examinationBatchDO.setRemark(remark);//未通过，添加备注
                    } else {
                        examinationBatchDO.setRemark("");//审核通过，清空备注
                    }
                    boolean b = examinationBatchService.updateById(examinationBatchDO);
                    if (b) {
                        i++;
                    } else {
                        break;
                    }
                }
            }
            if (i == ids.length) {
                return Result.build(0, "已成功审核：" + i + "条数据");
            } else {
                return Result.fail("审核状态修改失败！");
            }
        } else {
            return Result.fail("审核状态修改失败！");
        }
    }

    @Log("生成试卷")
    @ResponseBody
    @PostMapping("/generateTestPaper")
    @RequiresPermissions("jzweb:examinationBatch:generateTestPaper")
    @Transactional
    public Result<String> generateTestPaper(Long id) {
        //第一步，判断参数信息
        if (id == null) {
            return Result.fail("缺少参数：ebatchId！");
        }

        //第二步，查询考试批次信息
        ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(id);
        if (examinationBatchDO == null) {
            return Result.fail("对应的考试批次信息有误，请检查或重试！");
        } else {
            if (examinationBatchDO.getState().equals(0) || examinationBatchDO.getState().equals(2)) {
                return Result.fail("该考试批次审核还未通过，请先审核！");
            } //查询认证批次信息
            CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(examinationBatchDO.getCbatchId());
            if (certificationBatchDO == null) {
                return Result.fail("对应的认证批次信息有误，请检查或重试！");
            }
            //查询试卷模板信息
            TestPaperTemplateDO testPaperTemplateDO = testPaperTemplateService.findOneByKv( "news_id", certificationBatchDO.getNewsId());

            if (testPaperTemplateDO == null) {
                return Result.fail("未找到对应的试卷模板，请检查或重试！");
            } else {

                /**
                 * 通过题库现有题目数量，再根据试卷模板配置的题目数量 生成最大数量的试卷
                 */
                //查询现有题库数量
                List<ItemBankDO> itemBankList = itemBankService.selectList(new EntityWrapper<ItemBankDO>().eq("state", 1));
                int type0 = 0;//单选
                int type1 = 0;//多选
                int type2 = 0;//判断
                //int type4 = 0;//制定照护计划
                if(null!=itemBankList && !itemBankList.isEmpty()){
                    for (ItemBankDO itemBankDO : itemBankList) {
                        if(itemBankDO.getTopicTypes()==0){
                            type0+=1;
                        } else if (itemBankDO.getTopicTypes()==1) {
                            type1+=1;
                        } else if (itemBankDO.getTopicTypes()==2) {
                            type2+=1;
                        } /*else if (itemBankDO.getTopicTypes()==4) {
                            type4+=1;
                        }*/
                    }
                }
                //查询试卷模板配置的每种题型的数量
                int templateType4 = 0;//单选
                int templateType5 = 0;//多选
                int templateType6 = 0;//判断
                //int templateType7 = 0;//制定照护计划
                List<TemplateDetailsDO> templateList = templateDetailsService.selectList(new EntityWrapper<TemplateDetailsDO>().eq("tptemplate_id", testPaperTemplateDO.getId()));
                if(null!=templateList && !templateList.isEmpty()){
                    for (TemplateDetailsDO templateDetailsDO : templateList) {
                        if(templateDetailsDO.getType()==4){
                            templateType4 = templateDetailsDO.getTitleNumber();
                        } else if (templateDetailsDO.getType()==5) {
                            templateType5 = templateDetailsDO.getTitleNumber();
                        } else if (templateDetailsDO.getType()==6) {
                            templateType6 = templateDetailsDO.getTitleNumber();
                        } /*else if (templateDetailsDO.getType()==7) {
                            templateType7 = templateDetailsDO.getTitleNumber();
                        }*/
                    }
                }
                //i就是需要生成的试卷数量
                int num = 0;
                //制定照护计划
                /*if(examinationBatchDO.getType()==1){
                    num = type4 / templateType7;
                }*/
                //职业素养测评
                /*else*/ if (examinationBatchDO.getType()==2) {
                    //生成的试卷要根据最小值来判断
                    int i1 = type0 / templateType4;
                    int i2 = type1 / templateType5;
                    int i3 = type2 / templateType6;

                    num = i1;
                    if (i2 < num) {
                        num = i2;
                    }
                    if (i3 < num) {
                        num = i3;
                    }
                }
                //先查询当前竞赛下 已经有几套试卷 生成的试卷按照命名规则（第1套、第2套.....命名）
                int sort =0;
                Wrapper<ExaminationPaperDO> eq = new EntityWrapper<ExaminationPaperDO>().eq("ebatch_id", id).orderBy("sort", false);
                List<ExaminationPaperDO> examinationPaperComDOS = examinationPaperService.selectList(eq);
                if (examinationPaperComDOS != null && !examinationPaperComDOS.isEmpty()) {
                    sort = examinationPaperComDOS.get(0).getSort();
                }
                if(num!=0){
                    for (int kk = 1; kk <= num; kk++) {
                        /**
                         * 新建试卷
                         */
                        int ii = kk + sort;
                        ExaminationPaperDO examinationPaperDO1 = new ExaminationPaperDO();
                        examinationPaperDO1.setEbatchId(id);//考试批次id
                        examinationPaperDO1.setTptemplateId(testPaperTemplateDO.getId());//试卷模板id
                        examinationPaperDO1.setName("第"+ii+"套");//试卷名称
                        examinationPaperDO1.setSort(ii);
                        examinationPaperDO1.setState(1);//状态
                        examinationPaperDO1.setType(examinationBatchDO.getType());//竞赛类型
                        examinationPaperDO1.setDuration(testPaperTemplateDO.getDuration());//时长
                        examinationPaperDO1.setCreaterId(this.getUserId());//创建人id
                        examinationPaperDO1.setCreaterDate(new Date());//创建时间
                        boolean b1 = examinationPaperService.insert(examinationPaperDO1);
                        if (!b1) {
                            return Result.fail("生成试卷失败，请稍后重试！");
                        }



                        List<ExaminationQuestionsDO> examinationQuestionsDOS = new ArrayList<>();
                        //查询试卷模板详情
                        List<TemplateDetailsDO> templateDetailsDOs = templateDetailsService.findByKv("tptemplate_id", testPaperTemplateDO.getId());
                        if (templateDetailsDOs != null && templateDetailsDOs.size() > 0) {
                            //获得试卷模板的题目组成
                            int one = 0;//暂定单选
                            int two = 0;//暂定多选
                            for (TemplateDetailsDO templateDetailsDO : templateDetailsDOs) {
                                if (templateDetailsDO.getType() == 0||templateDetailsDO.getType() == 3) {
                                    one = one + templateDetailsDO.getTitleNumber();
                                } else if (templateDetailsDO.getType() == 1||templateDetailsDO.getType() == 4) {
                                    two = two + templateDetailsDO.getTitleNumber();
                                }
                            }

                            int singleNum = 1;
                            int multipleNum = one + 1;
                            int judgeNum = one + two + 1;
                            System.out.println(multipleNum+"   "+judgeNum);
                            //从题库中查询并将信息添加至试卷试题
                            Long kid=null;
                            for (TemplateDetailsDO templateDetailsDO : templateDetailsDOs) {
                                //暂时去除实操题的生成
                                if (1 == 1) {//templateDetailsDO.getType() != 6
                                    CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(certificationBatchDO.getNewsId());
                                    if (certificateNewsDO != null) {
                                        Map<Object, Object> map = new HashMap<>();
                                        map.put("kpointsId", templateDetailsDO.getKpointsId());
                                        kid=templateDetailsDO.getKpointsId();
                                        map.put("profileId", certificationBatchDO.getProfileId());
//                                        map.put("topicTypes", templateDetailsDO.getType()%3);
                                        if (templateDetailsDO.getType()%3 == 1 && templateDetailsDO.getType() == 7){
                                            map.put("topicTypes", 4);
                                        }else {
                                            map.put("topicTypes", templateDetailsDO.getType()%4);
                                        }
                                        System.out.println("kpointsId="+templateDetailsDO.getKpointsId());
                                        System.out.println("profileId="+certificationBatchDO.getProfileId());

                                        if (certificateNewsDO.getGrade() == 0) {
                                            map.put("grade", "高级");
                                        } else if (certificateNewsDO.getGrade() == 1) {
                                            map.put("grade", "中级");
                                        } else if (certificateNewsDO.getGrade() == 2) {
                                            map.put("grade", "初级");
                                        }


                                        map.put("titleNumber", templateDetailsDO.getTitleNumber());
                                        if(templateDetailsDO.getType()>=3) {
                                            map.put("item_bank_type", "1");//考试题
                                        }else {
                                            map.put("item_bank_type", "0");//练习题
                                        }
                                        List<Map<Object, Object>> maps = itemBankService.selRandList(map);


                                        if (maps != null && maps.size() == templateDetailsDO.getTitleNumber()) {
                                            for (int i = 0; i < maps.size(); i++) {
                                                ExaminationQuestionsDO examinationQuestionsDO = new ExaminationQuestionsDO();
                                                examinationQuestionsDO.setEpaperId(examinationPaperDO1.getId());//考试试卷id
                                                examinationQuestionsDO.setType((Integer) maps.get(i).get("topicTypes"));//题目类型
                                                examinationQuestionsDO.setIntroduce(maps.get(i).get("topicContent").toString());//题目描述
                                                if(examinationBatchDO.getType()==2){
                                                    examinationQuestionsDO.setOptions(maps.get(i).get("options").toString());//题目选项
                                                    examinationQuestionsDO.setAnswers(maps.get(i).get("rightKey").toString());//答案
                                                }
                                                //题目题干内容类型 0 文字 1 图片 2 视频
                                                examinationQuestionsDO.setResourceType((Integer)maps.get(i).get("resourceType"));
                                                //资源URL
                                                examinationQuestionsDO.setResourceUrl((String) maps.get(i).get("resourceUrl"));
//                                                if(examinationQuestionsDO.getType() == 4 && examinationQuestionsDO.getResourceType() == 2 && !StringUtil.notEmpty(examinationQuestionsDO.getResourceUrl())){
//                                                    return Result.fail("请上传案例分析题视频！");
//                                                }
                                                examinationQuestionsDO.setScore(templateDetailsDO.getScore());//分值
                                                if ((Integer) maps.get(i).get("topicTypes")== 0) {//单选
                                                    examinationQuestionsDO.setTitleNumber(singleNum);//题号
                                                    singleNum = singleNum + 1;
                                                } else if ((Integer) maps.get(i).get("topicTypes") == 1) {//多选
                                                    examinationQuestionsDO.setTitleNumber(multipleNum);//题号
                                                    multipleNum = multipleNum + 1;
                                                } else if ((Integer) maps.get(i).get("topicTypes") == 2) {//判断
                                                    examinationQuestionsDO.setTitleNumber(judgeNum);//题号
                                                    judgeNum = judgeNum + 1;
                                                }/*else if ((Integer) maps.get(i).get("topicTypes") == 4) {//制定照护计划
                                                    examinationQuestionsDO.setTitleNumber(judgeNum);//题号
                                                    judgeNum = judgeNum + 1;
                                                }*/

                                                examinationQuestionsDOS.add(examinationQuestionsDO);
                                            }
                                        } else {
                                            examinationPaperService.deleteById(examinationPaperDO1.getId());//删除试卷
                                            KnowledgePointsDO k = knowledgePointsService.selectById(templateDetailsDO.getKpointsId());
                                            String errorMsg="试卷模板中知识点(";
                                            errorMsg+=k.getName();
                                            if(map.get("item_bank_type").toString().equals("1")){
                                                errorMsg+="/考试题库";
                                            }else{
                                                errorMsg+="/练习题库";
                                            }
                                            if(map.get("topicTypes").toString().equals("0")){
                                                errorMsg+="/单选题";
                                            }else if(map.get("topicTypes").toString().equals("1")){
                                                errorMsg+="/多选题";
                                            }else {
                                                errorMsg+="/判断题";
                                            }
                                            errorMsg+=")暂无相应题目，已为您删除生成的试卷，请检查并稍后重试！";
                                            return Result.fail(errorMsg);
                                        }
                                    } else {
                                        examinationPaperService.deleteById(examinationPaperDO1.getId());//删除试卷
                                        return Result.fail("认证批次中的证书信息等级有误，已为您删除生成的试卷，请检查并稍后重试！");
                                    }
                                }
                            }
                            Map<Object, Object> map1 = new HashMap<>();
                            map1.put("kpointsId", kid);
                            map1.put("profileId", certificationBatchDO.getProfileId());
                            map1.put("topicTypes", 5);
                            map1.put("titleNumber", 1);
                            map1.put("grade", "级");
                            map1.put("item_bank_type", 2);

                            List<Map<Object, Object>> maps1 = itemBankService.selRandList(map1);
                            boolean b=false;
                            for (int i = 0; i < maps1.size(); i++) {
                                ExaminationQuestionsDO examinationQuestionsDO = new ExaminationQuestionsDO();
                                examinationQuestionsDO.setEpaperId(examinationPaperDO1.getId());//考试试卷id
                                examinationQuestionsDO.setType((Integer) maps1.get(i).get("topicTypes"));//题目类型
                                examinationQuestionsDO.setIntroduce(maps1.get(i).get("topicContent").toString());//题目描述
                                examinationQuestionsDO.setTitleNumber(examinationQuestionsDOS.size()+1);//题号
                                examinationQuestionsDOS.add(examinationQuestionsDO);
                            }


                            b = examinationQuestionsService.insertBatch(examinationQuestionsDOS);
                            if (!b) {

                                examinationPaperService.deleteById(examinationPaperDO1.getId());//删除试卷
                                return Result.fail("对应知识点没有对应的案例分析题，为您删除生成的试卷，请检查并稍后重试！！");


                            }else{
                                examinationBatchDO.setState(6);//考试批次状态改为已生成考卷
                                boolean bbd = examinationBatchService.updateById(examinationBatchDO);
                                if (!bbd) {
                                    return Result.fail("考试批次状态修改失败，考卷已生成，请删除考卷重新生成或联系管理员！");
                                }
                                continue;
                            }

                        } else {
                            examinationPaperService.deleteById(examinationPaperDO1.getId());//删除试卷
                            return Result.fail("试卷模板详情信息有误或没有信息，已为您删除生成的试卷，请检查并稍后重试！");
                        }
                    }
                }else {
                    return Result.fail("题库不存在试题或者试卷模板异常或者竞赛类型为空");
                }

            }
            return Result.ok("试卷生成成功！");
        }
    }




    @Log("阅卷")
    @ResponseBody
    @PostMapping("/markingPapers")
    @RequiresPermissions("jzweb:examinationBatch:markingPapers")
    @Transactional
    public Result<String> markingPapers(Long examBatchId,String field) {
        apittController.mk(examBatchId,field);
        return Result.ok("阅卷中");
    }
    
    private double results(String answers,List<Long> idss) {
        double results = 0;
        if(StringUtils.isNotBlank(answers)){
            JSONArray jsonArray2 = JSONArray.fromObject(answers);
            for(int i = 0;i<jsonArray2.size();i++){
                if(idss.indexOf(Long.parseLong(jsonArray2.getJSONObject(i).getString("id"))) > -1){
                    ExaminationQuestionsDO examinationQuestionsDO = examinationQuestionsService.selectById(Long.parseLong(jsonArray2.getJSONObject(i).getString("id")));
                    if (examinationQuestionsDO.getType() == 0 || examinationQuestionsDO.getType() == 2) {//单选题和判断题，答案唯一，可以不用拆解了
                        if (examinationQuestionsDO.getAnswers().equals(jsonArray2.getJSONObject(i).getString("value"))) {
                            results = results + examinationQuestionsDO.getScore();
                        }
                    } else if (examinationQuestionsDO.getType() == 1) {//多选题因为答案有多个，需要循环判断一下是否包含该答案
                        boolean isRight=true;
                        if(jsonArray2.getJSONObject(i).getString("value")==null||jsonArray2.getJSONObject(i).getString("value")==""){
                            isRight=false;
                        }else{
                            String[] ssb = jsonArray2.getJSONObject(i).getString("value").split(";;");
                            String answer = examinationQuestionsDO.getAnswers();
                            if(ssb.length!=answer.split(";;").length){
                                isRight=false;
                            }else {
                                for (int n = 0; n < ssb.length; n++) {
                                    //if (ssb[n].equals("A") || ssb[n].equals("B") || ssb[n].equals("C") || ssb[n].equals("D") || ssb[n].equals("E") || ssb[n].equals("F")) {
                                    if (!answer.contains(ssb[n])) {
                                        isRight = false;
                                        break;
                                    }

                                }
                            }
                        }

                        if (isRight) {
                            results = results + examinationQuestionsDO.getScore();
                        }

                    }
                }
            }
        }

        return results;
    }
    /**
     * 抽取试卷页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/trackDraw/{id}")
    String trackDraw(@PathVariable("id") Long id, Model model) {
        String jsonString = null;
        Wrapper<ExaminationPaperDO> wrapper = new EntityWrapper<ExaminationPaperDO>().eq("ebatch_id", id);
        List<ExaminationPaperDO> examinationPaperDOS = examinationPaperService.selectList(wrapper);
        if(null!=examinationPaperDOS && !examinationPaperDOS.isEmpty()){
            jsonString = JSON.toJSONString(examinationPaperDOS);
        }
        model.addAttribute("trackDraw",jsonString);
        model.addAttribute("cbatchId",id);
        return "jzweb/examinationBatch/trackDraw";
    }

    /**
     * 抽取试卷全屏页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/trackDrawFull/{id}")
    String trackDrawFull(@PathVariable("id") Long id, Model model) {
        String jsonString = null;
        Wrapper<ExaminationPaperDO> wrapper = new EntityWrapper<ExaminationPaperDO>().eq("ebatch_id", id);
        List<ExaminationPaperDO> examinationPaperDOS = examinationPaperService.selectList(wrapper);
        if(null!=examinationPaperDOS && !examinationPaperDOS.isEmpty()){
            jsonString = JSON.toJSONString(examinationPaperDOS);
        }
        model.addAttribute("trackDraw",jsonString);
        model.addAttribute("cbatchId",id);
        return "jzweb/examinationBatch/trackDrawFull";
    }

    @ResponseBody
    @GetMapping("/trackDrawList")
    public Result<ExaminationPaperDO> trackDrawList(Long cbatchId){

        return examinationPaperService.trackDrawList(cbatchId);
    }


    /**
     * 抽签确认
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("/confirmation/{id}")
    Result<?> confirmation(@PathVariable("id") Long id) {
        ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(id);
        examinationPaperDO.setState(99);
        examinationPaperService.updateById(examinationPaperDO);
        return Result.ok();
    }


    /**
     * 开始考试
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("/startExam")
    public Result<?> startExam(Long id){
        ExaminationBatchComDO examinationBatchComDO = examinationBatchService.selectById(id);
        if(null==examinationBatchComDO){
            Result.fail("考试不存在！");
        }
        examinationBatchComDO.setState(4);
        examinationBatchService.updateById(examinationBatchComDO);
        return Result.ok("考试已开启！");
    }


}
